<template>
  <section class="todoapp">
    <!-- 使用 -->
    <TodoListHeader @addbtn="addbtn"></TodoListHeader>
    <TodoListBody
      :List="renderList"
      @changeFlag="changeFlag"
      @delbtn="delbtn"
      @changeAll="changeAll"
    ></TodoListBody>
    <TodoListFooter
      :sum="sum"
      @delAll="delAll"
      :type="type"
      @changeType="changeType"
      :isShow="isShow"
    ></TodoListFooter>
  </section>
</template>

<script>
// 引入
import TodoListHeader from './components/TodoListHeader'
import TodoListBody from './components/TodoListerBody'
import TodoListFooter from './components/TodoListFooter'
export default {
  data() {
    return {
      List:JSON.parse(localStorage.getItem("getList")) || [
        {
          flag: true,
          sum: '读万卷书',
          id: 1,
        },
        {
          flag: false,
          sum: '行万里路',
          id: 2,
        },
      ],
      type: 'all',
    }
  },
  methods: {
    // 添加数据
    addbtn(value) {
      this.List = [
        ...this.List,
        {
          flag: false,
          sum: value,
          id: +new Date(),
        },
      ]
    },
    // 改变flag的值，将对于的数据加上样式
    changeFlag(id, value) {
      this.List.forEach((item) => (item.id === id ? (item.flag = value) : ''))
    },
    // 删除事件
    delbtn(id) {
      this.List = this.List.filter((item) => item.id !== id)
    },
    // 清除已完成的事件
    delAll() {
      this.List = this.List.filter((item) => !item.flag)
    },
    // 修改type属性值
    changeType(value) { 
      this.type=value
    },
    // 全选和反选
    changeAll(value){
      this.List.forEach(item=>item.flag=value)
    }
  },
  // 计算属性
  computed: {
    sum() {
      return this.List.filter((item) => !item.flag).length
    },
    renderList() {
      switch (this.type) {
        case 'all':
          return this.List
        case 'active':
          return this.List.filter(item=>!item.flag)
        case 'completed':
          return this.List.filter(item=>item.flag)
          default:
            return this.List
      }
    },
    isShow(){
      return this.List.some(item=>item.flag)
    }
  },
  watch:{
    // 监听List 一发生变化将新数据存储到本地
    List:{
      immediate:true,
      deep:true,
      handler(newval){
        localStorage.setItem("getList",JSON.stringify(newval))
      }
    }
  },
  // 注册
  components: {
    TodoListHeader,
    TodoListBody,
    TodoListFooter,
  },
}
</script>

<style></style>
